#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
        vector<vector<int>> ans;
        int len = intervals.size();
        if (len == 0)return { {newInterval[0],newInterval[1]} };
        int l = newInterval[0];
        int r = newInterval[1];
        int f = 0;
        int flag = 0;
        if (intervals[0][0] > r) {
            ans.push_back({ l,r });
            flag = 1;
        }
        int lm = l;
        int rm = r;

        for (int i = 0; i < len; i++) {
            if (intervals[i][1]<l || intervals[i][0]>r) {
                if (f == 1) {
                    ans.push_back({ lm,rm });
                    flag = 1;
                    f = 0;
                }
                ans.push_back(intervals[i]);
            }
            else {
                //if(f==1)continue;
                lm = min(lm, intervals[i][0]);
                rm = max(rm, intervals[i][1]);
                f = 1;
                //ans.push_back({lm,rm});
            }
        }
        if (f == 1 || flag == 0) {
            ans.push_back({ lm,rm });
            flag = 1;
        }
        sort(ans.begin(), ans.end());

        return ans;
    }
};